/* 
 *  Copyright 2009-2010 Michal Trzcinka
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software distributed
 *  under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 *  CONDITIONS OF ANY KIND, either express or implied. See the License for the
 *  specific language governing permissions and limitations under the License.
 */
YAHOO.namespace('TRZCINKA.VCARD');

(function() {

  var Dom = YAHOO.util.Dom,
  JSON = YAHOO.lang.JSON,
  Config = YAHOO.TRZCINKA.VCARD.Config, 
  LOGGER = new YAHOO.widget.LogWriter('item_editor.js');

  YAHOO.TRZCINKA.VCARD.ItemEditor = function(gridModel) {
    this._gridModel = gridModel;
    this._DIALOG_CONTAINER_ID = Dom.generateId();
    this._TEXTAREA_ID = Dom.generateId();

    var dialogContainer = document.createElement('div');
    dialogContainer.id = this._DIALOG_CONTAINER_ID;
    var body = document.createElement('div');
    Dom.addClass(body, 'bd');
    dialogContainer.appendChild(body);
    var textarea = document.createElement('textarea');
    textarea.id = this._TEXTAREA_ID;
    body.appendChild(textarea);

    document.body.appendChild(dialogContainer);

    this._finishHandler = null;
    this._editor = this._initEditor();
    this._dlg = this._initDialog();
    this._insertImageDlg = this._initInsertImageDlg();

  }
  
  YAHOO.TRZCINKA.VCARD.ItemEditor.prototype._initEditor = function() {
    var that = this;
    var editor = new YAHOO.widget.Editor(this._TEXTAREA_ID, {
      width: '702px',
      height: '200px',
      insert: true,
      toolbar: {
        collapse: false,
        titlebar: I18n.t('editor.item_editor.title'),
        draggable: false,
        buttons: [
        {
          group: 'fontstyle',
          label: 'Font Size',
          buttons: [
          {
            type: 'spin',
            label: '13',
            value: 'fontsize',
            range: [ 9, 75 ],
            disabled: false
          }
          ]
        },
        {
          type: 'separator'
        },
        {
          group: 'textstyle',
          label: 'Font Style',
          buttons: [
          {
            type: 'push',
            label: 'Bold CTRL + SHIFT + B',
            value: 'bold'
          },
          {
            type: 'push',
            label: 'Italic CTRL + SHIFT + I',
            value: 'italic'
          },
          {
            type: 'push',
            label: 'Underline CTRL + SHIFT + U',
            value: 'underline'
          },
          {
            type: 'separator'
          },
          {
            type: 'color',
            label: 'Font Color',
            value: 'forecolor',
            disabled: true
          },
          {
            type: 'color',
            label: 'Background Color',
            value: 'backcolor',
            disabled: true
          },
          {
            type: 'push',
            label: 'Remove Formatting',
            value: 'removeformat',
            disabled: true
          },
          ]
        },
        {
          type: 'separator'
        },
        {
          group: 'insertitem',
          label: 'Insert Item',
          buttons: [
          {
            type: 'push',
            label: 'HTML Link CTRL + SHIFT + L',
            value: 'createlink',
            disabled: true
          },
          {
            type: 'push',
            label: 'Insert Image',
            value: 'insertimage'
          }
          ]
        }
        ]
      }
    });
    editor.on('afterRender', editor.hide);

    editor.on('toolbarLoaded', function() {
      this.toolbar.on('insertimageClick', function() {
        var _sel = this._getSelectedElement();
        if (_sel && _sel.tagName && (_sel.tagName.toLowerCase() == 'img')) {
        //Do the normal thing here..
        } else {
          that._showInsertImageDialog();
          return false;
        }
      }, this, true);
    }, editor, true);
    editor.on('afterOpenWindow', function() {
      //When the window opens, disable the url of the image so they can't change it
      var url = Dom.get('insertimage_url');
      if (url) {
        url.disabled = true;
      }
    }, editor, true);

    editor.render();

    return editor;
  }

  YAHOO.TRZCINKA.VCARD.ItemEditor.prototype._initDialog = function() {
    var that = this;

    var dlg = new YAHOO.widget.Dialog(this._DIALOG_CONTAINER_ID, {
      width:"725px",
      fixedcenter:true,
      modal:true,
      visible:false,
      close: false
    });


    var buttons = [
    {
      text: I18n.t('editor.item_editor.save'),
      handler:function() {
        that._editor.saveHTML();
        var content =  that._editor.get('element').value;
        if (content.length < Config.MAX_ITEM_TEXT_LENGTH) {
          that._finishHandler(that._editor.get('element').value);
          dlg.hide();  
        } else {
          popup(I18n.t('editor.errors.too_long', {
            maxLength: Config.MAX_ITEM_TEXT_LENGTH
          }));
        }

      }
    },
    {
      text: I18n.t('editor.item_editor.cancel'),
      handler:function() {
        dlg.hide();
      }
    }
    ];
    dlg.cfg.queueProperty("buttons", buttons);

    dlg.render();

    dlg.showEvent.subscribe(this._editor.show, this._editor, true);
    dlg.hideEvent.subscribe(this._editor.hide, this._editor, true);

    return dlg;
  }

  YAHOO.TRZCINKA.VCARD.ItemEditor.prototype._showInsertImageDialog = function() {
    this._insertImageDlg.show();
  }

    
  YAHOO.TRZCINKA.VCARD.ItemEditor.prototype._initInsertImageDlg = function() {
    var that = this;
    var ID = Dom.generateId();
    var div = document.createElement('div');
    div.id = ID;

    var body = document.createElement('div');
    Dom.addClass(body, 'bd');
    div.appendChild(body);

    var errors = document.createElement('div');
    body.appendChild(errors);

    var form = document.createElement('form');
    form.name = 'image';
    form.method = 'POST';
    form.action = '/images/create';
    body.appendChild(form);

    var fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.name = 'file';
    form.appendChild(fileInput);

    var gridIdInput = document.createElement('input');
    gridIdInput.type = 'hidden';
    gridIdInput.name = 'grid_id';
    gridIdInput.value = this._gridModel.getGridId();
    form.appendChild(gridIdInput);

    document.body.appendChild(div);

    var dlg = new YAHOO.widget.Dialog(ID, {
      width:"725px",
      fixedcenter:true,
      modal:true,
      visible:false,
      close: true,
      hideaftersubmit: false
    });

    dlg.beforeShowEvent.subscribe(function() {
      errors.innerHTML = '';
      fileInput.value = '';
    });

    var buttons = [
    {
      text:"Upload",
      handler:dlg.submit
    },
    {
      text:"Cancel",
      handler:dlg.hide
    }
    ];
    dlg.cfg.queueProperty("buttons", buttons);

    dlg.callback.upload = function(o) {
      var response = JSON.parse(o.responseText);
      if (response.url) {
        dlg.hide();
        that._editor.execCommand('insertimage', response.url);
      } else {
        var text = '';
        response.each(function(error) {
          text += error[0] + ' ' + error[1] + '<br>';
        });
        errors.innerHTML = text;
      }
    };
    dlg.render();
    return dlg;
  }

    
  YAHOO.TRZCINKA.VCARD.ItemEditor.prototype.show = function(content, p_finishHandler) {
    this._editor.setEditorHTML(content);
    this._finishHandler = p_finishHandler;
    this._dlg.show();
  };

})();
